import { type EmailOtpType } from '@supabase/supabase-js'
import { type NextRequest } from 'next/server'
import { createClient } from '@/utils/supabase/server'
import { redirect } from 'next/navigation'

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const token_hash = searchParams.get('token_hash')
    const type = searchParams.get('type') as EmailOtpType | null
    const code = searchParams.get('code')
    
    const supabase = await createClient()
    const baseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL

    if (code) {
      const { error } = await supabase.auth.exchangeCodeForSession(code)
      if (!error) {
        return redirect(baseUrl)
      }
    }

    if (token_hash && type) {
      const { error } = await supabase.auth.verifyOtp({
        type,
        token_hash,
      })
      if (!error) {
        return redirect(baseUrl)
      }
    }

    return redirect(`${baseUrl}/error`)
  } catch (error) {
    console.error('Auth confirmation error:', error)
    return redirect(`${baseUrl}/error`)
  }
}